import React from 'react';
import BraftEditor from 'braft-editor'
import 'braft-editor/dist/index.css'
import { imgPrefix as prefix, miniPro } from '@/utils/constants';
// @ts-ignore
import Cookies from 'js-cookie';
import { replaceImgHost } from '@/utils/utils';

const Index: React.FC<any> = (props) => {
  const { setEditorState, editorState, readOnly, ref } = props
  return <BraftEditor
    readOnly={readOnly}
    onChange={setEditorState} 
    
    excludeControls={[
      'remove-styles',
      'code',
      'emoji'
    ]}
    media={{
      uploadFn: (param) => {
        const serverURL = '/api/common/image/batch/upload-compress'
        const xhr = new XMLHttpRequest
        const fd = new FormData()
        
        const successFn = (response: any) => {
          // 假设服务端直接返回文件上传后的地址
          // 上传成功后调用param.success并传入上传后的文件地址
          const fileList = JSON.parse(xhr.responseText)

          // @ts-ignore
          param.success({
            url: replaceImgHost(miniPro + fileList[0].file_web_url)
          })
        }

        const progressFn = (event: any) => {
          // 上传进度发生变化时调用param.progress
          param.progress(event.loaded / event.total * 100)
        }

        const errorFn = (response: any) => {
          // 上传发生错误时调用param.error
          param.error({
            msg: '文件上传失败'
          })
        }
        xhr.upload.addEventListener("progress", progressFn, false)
        xhr.addEventListener("load", successFn, false)
        xhr.addEventListener("error", errorFn, false)
        xhr.addEventListener("abort", errorFn, false)
        fd.append('file', param.file)
        xhr.open('POST', serverURL, true)
        xhr.setRequestHeader('Oper-Token', localStorage.getItem('Oper-Token'));
        xhr.send(fd)
      }
    }}
    value={editorState} />
}

export default Index